package com.mjw.tender.aop;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.mjw.tender.annotation.AvoidRepeatableCommit;
import com.mjw.tender.dto.ResponseResult;
import com.mjw.tender.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Aspect
public class AvoidRepeatableCommitAspect {
    @Resource
    private RedisTemplate redisTemplate;


    @Pointcut("@annotation(com.mjw.tender.annotation.AvoidRepeatableCommit)")
    public void repeatableCommitPointcut(){
    }

    @Before("repeatableCommitPointcut()")
    public void Before(){
        System.out.println("before");
    }

    @AfterReturning("repeatableCommitPointcut()")
    public void afterRunning(){
        System.out.println("afterRunning");
    }

    @After("repeatableCommitPointcut()")
    public void after(){
        System.out.println("after");
    }



    /**
     * @param point
     */
    @Around("repeatableCommitPointcut()")
    public ResponseResult around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("around begin");
        HttpServletRequest request  = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = UserAgentUtil.getIpAddr(request);
        //获取注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //目标类、方法
        String className = method.getDeclaringClass().getName();
        String name = method.getName();
        String ipKey = String.format("%s#%s",className,name);
        int hashCode = Math.abs(ipKey.hashCode());

        String key = Constants.REDIS_ROOT+String.format("%s_%d",ip,hashCode);

        log.info("ipKey={},hashCode={},key={}",ipKey,hashCode,key);
        AvoidRepeatableCommit avoidRepeatableCommit =  method.getAnnotation(AvoidRepeatableCommit.class);
        long timeout = avoidRepeatableCommit.timeout();
        if (timeout < 0){
            timeout = 3*Constants.SECOND;
        }
        String value = (String) redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(value)){
            return new ResponseResult(ResponseResult.CodeStatus.FAIL,"发送相同内容过于频繁");
        }
        redisTemplate.opsForValue().set(key, UUID.randomUUID().toString(),timeout, TimeUnit.MILLISECONDS);
        //执行方法
        ResponseResult result = (ResponseResult) point.proceed();
        System.out.println("around end");
        return result;
    }


}
